<template>
<div>
    <el-dialog :visible.sync="dialogVisible" @close="closeDialog">
        <h3>请假申请</h3>
        <el-form inline>
            <el-row :gutter="20" style="margin-top: 20px;">
                <el-col>
                    <el-form-item label="员工姓名">
                        <el-input v-model="empInfo.ename" disabled style="width:160px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-input v-model="empInfo.dname" disabled style="width:160px"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 20px;">
                <el-col>
                    <el-form-item label="毕业院校">
                        <el-input v-model="empInfo.college" disabled style="width:160px"></el-input>
                    </el-form-item>
                    <el-form-item label="入职日期">
                        <el-input v-model="empInfo.hiredate" disabled style="width:160px"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-form ref="form" :model="absenceForm" label-width="110px" :disabled="canbedit != 1 " :rules="rules">
            <el-row :gutter="20">
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="请假类型" prop="type">
                        <el-select v-model="absenceForm.type" placeholder="请选择请假类型" @change="changeType" style="width: 300px;">
                            <el-option v-for="type in absenceType" :label="type.name" :value="parseInt(type.value)" :key="type.absenceId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="请假开始时间" prop="startTime">
                        <el-date-picker style="width: 300px;" v-model="absenceForm.startTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" default-time="08:00:00" @change="chkTime1">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="请假结束时间" prop="planEndTime">
                        <el-date-picker style="width: 300px;" v-model="absenceForm.planEndTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" default-time="08:00:00" @change="chkTime2">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="计划请假天数">
                        <el-input style="width: 300px;" v-model="absenceForm.planDays" placeholder="选择请假时间后生成" disabled></el-input>
                    </el-form-item>
                </el-col>
                <template>
                    <el-alert :title="tip" type="warning" v-if="yearAbsenceFlag" :closable="false">
                    </el-alert>
                </template>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="15" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="请假事由" prop="reason">
                        <el-input type="textarea" :rows="4" placeholder="请输入请假事由" v-model="absenceForm.reason"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-form v-if="finishForm.realDays != ''" label-width="110px">
            <el-row :gutter="20">
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="实际销假时间">
                        <el-date-picker style="width: 300px;" v-model="finishForm.realEndTime" type="datetime" disabled>
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="实际请假天数">
                        <el-input style="width: 300px;" v-model="finishForm.realDays" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <hr>
        <h3>部门经理审核</h3>
        <el-form :model="absenceForm" label-width="100px" :disabled="canbedit != 2" :rules="rules">
            <el-row :gutter="20">
                <el-col :span="15" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="审核意见">
                        <el-input type="textarea" :rows="4" v-model="absenceForm.managerRes"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <hr>
        <h3>总经理审核</h3>

        <el-form :model="absenceForm" label-width="100px" :disabled="canbedit != 3" :rules="rules">
            <el-row :gutter="20">
                <el-col :span="15" :offset="3" style="margin-top: 20px;">
                    <el-form-item label="审核意见">
                        <el-input type="textarea" :rows="4" v-model="absenceForm.kingRes"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template v-if="btnCtrl==1">
            <el-button type="primary" @click="submit">保存</el-button>
            <el-button type="primary" @click="onsubmit">提交</el-button>
        </template>
        <template v-if="btnCtrl==2">
            <el-button type="warning" @click="calAbsence">撤回</el-button>
        </template>
        <template v-if="btnCtrl==3">
            <el-button type="warning" @click="finish">销假</el-button>
        </template>
        <template v-if="btnCtrl==4">
            <el-button type="warning" @click="reject">驳回</el-button>
            <el-button type="success" @click="pass">通过</el-button>
        </template>
        <el-button @click="cancle">返回</el-button>
    </el-dialog>
</div>
</template>

<script>
export default {
    name: "AbsenceInfo",
    props: {
        absenceType: Array,
        isShow: Boolean,
        empno: Number,
        id: Number,
        isSelf: Boolean,
    },
    data() {
        return {
            base: {
                id: '0',
                empno: '',
                deptno: '',
                type: '',
                startTime: '',
                planEndTime: '',
                planDays: '',
                reason: '',
                stage: '0',
                managerRes: '',
                kingRes: ''
            },
            absenceForm: {
                id: '0',
                empno: '',
                deptno: '',
                type: '',
                startTime: '',
                planEndTime: '',
                planDays: '',
                reason: '',
                stage: '0',
                managerRes: '',
                kingRes: ''
            },
            empInfo: {
                ename: '',
                deptno: '',
                dname: '',
                hiredate: '',
                college: ''
            },

            canbedit: 0,
            //入职年数
            hireYears: '',
            //年假天数
            yearDays: '',
            dialogVisible: false,
            btnCtrl: 0,
            finishForm: {
                realEndTime: '',
                realDays: ''
            },
            rules: {
                type: [{
                    required: true,
                    message: '请选择请假类型',
                    trigger: 'blur'
                }],
                startTime: [{
                    required: true,
                    message: '请选择请假开始时间',
                    trigger: 'blur'
                }],
                planEndTime: [{
                    required: true,
                    message: '请选择请假结束时间',
                    trigger: 'blur'
                }],
                reason: [{
                    required: true,
                    message: '请输入请假是由',
                    trigger: 'blur'
                }]
            },
            yearAbsenceFlag : false,
            //显式提示还剩多少天年假
            tip:''
        }
    },
    methods: {
        chkTime1() {
            let start = new Date(this.absenceForm.startTime);
            let now = new Date();
            if (start < now) {
                this.$message({
                    message: '请假开始时间不能早于当前时间',
                    type: 'warning'
                });
                this.absenceForm.startTime = '';
            }
            if (start.getUTCHours() > 10) {
                this.$message({
                    message: '请假开始时间不能早于上午8点,不能晚于下午6点',
                    type: 'warning'
                });
                this.absenceForm.startTime = '';
            }
        },
        chkTime2() {
            let start = new Date(this.absenceForm.startTime);
            let end = new Date(this.absenceForm.planEndTime);
            if (end.getUTCHours() > 10) {
                this.$message({
                    message: '请假结束时间不能早于上午8点,不能晚于下午6点',
                    type: 'warning'
                });
                this.absenceForm.planEndTime = '';
            }
            if (start != '' && end != '') {
                if (end <= start) {
                    this.$message({
                        message: '请假结束时间必须晚于开始时间',
                        type: 'warning'
                    });
                    this.absenceForm.planEndTime = '';
                } else {
                    let days = parseInt((end - start) / (1000 * 60 * 60 * 24));
                    let hours = (end - start) / (1000 * 60 * 60) % 24;
                    if (hours > 3 && hours <= 8) {
                        days += 0.5;
                    } else if (hours > 8) {
                        days += 1;
                    }
                    if (this.absenceForm.type == '1' && days > this.yearDays) {
                        this.$message({
                            message: '年假天数不足',
                            type: 'warning'
                        });
                        this.absenceForm.planEndTime = '';
                        this.absenceForm.planDays = '';
                    } else {
                        this.absenceForm.planDays = days;
                    }
                }
            }
        },
        changeType() {
            this.absenceForm.startTime = '';
            this.absenceForm.planEndTime = '';
            this.absenceForm.planDays = '';
            if(this.absenceForm.type == '1') {
                this.yearAbsenceFlag = true 
                this.getYearDays()
                this.tip = `年假剩余${this.yearDays}天`
            } else {
                this.yearAbsenceFlag = false
            }
        },
        closeDialog() {
            this.yearAbsenceFlag = false
            this.canbedit = 0
            debugger
            this.absenceForm = {...this.base}
            this.dialogVisible = false
            this.$emit('reload')
        },
        getEmpInfo() {
            this.$http.get('/getEmpInfo?empno=' + this.absenceForm.empno).then((res) => {
                if (res.data.code === 200) {
                    this.empInfo = res.data.data;
                    this.absenceForm.deptno = this.empInfo.deptno;
                    this.hireYears = new Date().getFullYear() - new Date(this.empInfo.hiredate).getFullYear();
                    this.getYearDays();
                    this.whoCanEdit()
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            });
        },
        //获取年假天数
        getYearDays() {
            this.$http.get("/getYearDays?years=" + this.hireYears + "&empno=" + localStorage.getItem("empno")).then((res) => {
                this.yearDays = res.data;
            })
        },
        submit(flag) {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.$http.post('/saveOrUpdate', this.absenceForm).then((res) => {
                        if (res.data === "success") {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            if (flag) {
                                this.closeDialog()
                            }
                        } else {
                            this.$message({
                                message: '服务器错误',
                                type: 'error'
                            });
                        }
                    }).catch((err) => {
                        console.log(err);
                    });
                } else {
                    console.log('请检查输入');
                    return false;
                }
            });
        },
        //保存
        keep() {
            this.submit(false)
        },
        //提交
        onsubmit() {
            let roleids = localStorage.getItem("roleid")
            let roleid = roleids.substring(0,1)
            if (roleid == '4') {
                //员工提交给部门经理
                this.absenceForm.stage = 1
            } else {
                //部门经理提交给总经理
                this.absenceForm.stage = 2
            }
            this.absenceForm.managerRes = ''
            this.absenceForm.kingRes = ''
            this.submit(true)
        },
        //驳回
        reject() {
            //判断是否填写审核意见
            if ((this.absenceForm.stage == '1' && this.absenceForm.managerRes != '') ||
                (this.absenceForm.stage == '2' && this.absenceForm.kingRes != '')) {
                this.absenceForm.stage = '0';
                
                this.submit(true)
            } else {
                this.$message({
                    message: '请填写审核意见',
                    type: 'warning'
                });
            }
        },
        //撤回
        calAbsence() {
            this.$confirm('确认要撤回该申请吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.absenceForm.stage = 0
                this.submit(false)
                this.whoCanEdit();

            }).catch(() => {
                this.$message({
                    message: '您已取消操作',
                    type: 'info'
                })
            })
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        //销假
        finish() {
            let now = new Date()
            let start = new Date(this.absenceForm.startTime)
            if (now < start) {
                this.$message({
                    message: '请假还没开始，无法销假',
                    type: 'error'
                })
            } else {
                let realDays = parseInt((now - start) / (1000 * 60 * 60 * 24));
                let hours = (now - start) / (1000 * 60 * 60) % 24;

                if (hours > 3 && hours <= 8) {
                    realDays += 0.5;
                } else if (hours > 8) {
                    realDays += 1;
                }
                if (realDays == 0) {
                    realDays = 0.5;
                }
                let realEndTime = this.formatDate(now)
                let updateAbsence = {
                    id: this.id,
                    realEndTime: realEndTime,
                    realDays: realDays,
                }
                this.$http.post('/finishAbsence', updateAbsence).then(res => {
                    if (res.data == 'success') {
                        this.$message({
                            message: '销假成功',
                            type: 'success'
                        })
                        this.closeDialog()
                    } else {
                        this.$message.error('服务器错误')
                    }
                })
            }
        },
        //审核通过
        pass() {
            let stage = this.absenceForm.stage
            let planDays = this.absenceForm.planDays
            if (stage == '1' && planDays > 5) {
                //请假天数大于5天交给总经理审核
                this.absenceForm.stage = 2
            } else {
                this.absenceForm.stage = 3
            }
            this.submit(true)
        },
        whichBtn() {
            let roleids = []
            roleids = localStorage.getItem("roleid")
            let roleid = roleids.substring(0,1)
            let stage = this.absenceForm.stage
            debugger
            if (this.isSelf) {
                if (stage == '0') {
                    //保存、提交
                    this.btnCtrl = 1
                } else if ((roleid == '4' && stage == '1') || (roleid == '3' && stage == '2')) {
                    //撤回
                    this.btnCtrl = 2
                } else if (stage == '3' && this.finishForm.realDays == '0') {
                
                    //销假
                    this.btnCtrl = 3
                }
            } else {
                if ((roleid == '3' && stage == '1') || (roleid == '2' && stage == '2')) {
                    //驳回、通过
                    this.btnCtrl = 4
                }
            }
        },
        whoCanEdit() {
            let roleids = localStorage.getItem("roleid")
            let roleid = roleids.substring(0,1)
            let stage = this.absenceForm.stage
            if ((roleid == '4' || roleid == '3') && stage == '0') {
                //员工或部门经理请假阶段
                this.canbedit = 1
            } else if (roleid == '3' && stage == '1') {
                //部门经理审核阶段
                this.canbedit = 2
            } else if (roleid == '2' && stage == '2') {
                //总经理审核阶段
                this.canbedit = 3
            }
            this.whichBtn()
        },
        cancle() {
            this.closeDialog()
        },
        getOneAbsence() {
            this.$http.get('/getOneAbsence?id=' + this.id).then((res) => {
                if (res.data.code === 200) {
                    this.absenceForm = {
                        ...res.data.data
                    };
                    this.finishForm = {
                        ...res.data.data
                    }
                    this.getEmpInfo()
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            });
        }
    },
    watch: {
        isShow() {
            this.dialogVisible = true
            if (this.id == '0') {
                this.absenceForm.empno = localStorage.getItem("empno")
                this.getEmpInfo()
            } else {
                this.getOneAbsence()
            }
        },
    }
}
</script>

<style></style>
